package com.xcc.shopanim.olda;

import android.app.Activity;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nineoldandroids.view.ViewHelper;
import com.xcc.shopanim.R;
import com.xcc.shopanim.adapter.SuperRecyclerAdapter;
import com.xcc.shopanim.mode.BannerMode;
import com.xcc.shopanim.mode.NewMainVideoMode;
import com.xcc.shopanim.utils.CenterLayoutManager;
import com.xcc.shopanim.utils.GlideUtils;
import com.xcc.shopanim.widget.VerticalDrawerLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;

public class LayoutDrawerViewHolder implements VerticalDrawerLayout.OnVerticalDrawerListener {
    public LayoutDrawerViewHolder(Activity activity, VerticalDrawerLayout drawerLayout, List<NewMainVideoMode> modeList) {
        this.drawerLayout = drawerLayout;
        this.activity = activity;
        this.modeList = modeList;
        //presenter = new LayoutDrawerViewPresenter(this);

        random = new Random();

        /*Resources res = activity.getResources();
        _小时前 = res.getString(R.string._小时前);
        _1小时 = res.getString(R.string._1小时);
        _1天 = res.getString(R.string._1天);
        _天前 = res.getString(R.string._天前);
        _小时内 = res.getString(R.string._小时内);
        _天内 = res.getString(R.string._天内);*/

        detailsModeMap = new HashMap<>(15);

        ButterKnife.bind(this, drawerLayout);

        drawerLayout.setOnVerticalDrawerListener(this);

        adapter = new LayoutDrawerAdapter(activity, modeList);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(layoutManager = new CenterLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false));

        Glide.with(activity).asGif()
                .load(R.raw.img_main_side_livegif_)
                .into(imgLive);
    }

    private Activity activity;
    //private LayoutDrawerViewPresenter presenter;
    private VerticalDrawerLayout drawerLayout;
    private List<NewMainVideoMode> modeList;
    private LayoutDrawerAdapter adapter;
    private LinearLayoutManager layoutManager;
    private OnLayoutDrawerListener onLayoutDrawerListener;
    private Map<NewMainVideoMode, Object> detailsModeMap;
    private int position;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.imgLive)
    ImageView imgLive;
    @BindView(R.id.textMakeAnLive)
    TextView textMakeAnLive;
    @BindView(R.id.imgArr)
    ImageView imgArr;
    @BindView(R.id.layout1Bg)
    View layout1Bg;
    @BindView(R.id.layout1)
    View layout1;
    @BindView(R.id.layout2)
    View layout2;
    private final Random random;
    private List<ViewHolderAnim> animList;
    private Runnable animRunnable;

    private void startChaseAnim(int paddingTop) {
        ViewHolderAnim holderAnimTmp;
        if (animList == null) {
            final int animCurrY = -drawerLayout.getContentHeight();
            holderAnimTmp = new ViewHolderAnim(animCurrY, paddingTop);
            animList = new ArrayList<>(5);
            animList.add(holderAnimTmp);//先创建一个
        } else {
            holderAnimTmp = animList.get(0);
            for (int i = 0; i < animList.size(); i++) {
                ViewHolderAnim holderAnim = animList.get(i);
                holderAnim.setAnimEndY(paddingTop);
            }
        }
        final int firstPosition = layoutManager.findFirstVisibleItemPosition();
        final int lastPosition = layoutManager.findLastVisibleItemPosition();
        List<View> viewList = new ArrayList<>();
        for (int i = firstPosition; i <= lastPosition; i++) {
            View view = layoutManager.findViewByPosition(i);
            if (view == null) continue;
            viewList.add(view);
        }

        for (int i = 0; i < viewList.size(); i++) {
            View view = viewList.get(i);
            ViewHolderAnim holderAnim;
            if (i < animList.size()) {
                holderAnim = animList.get(i);
            } else {
                holderAnim = holderAnimTmp.cloneAnim();
                animList.add(holderAnim);
            }
            int top = holderAnim.animCurrY - holderAnim.animEndY;
            setViewTop(view, top);
        }
        startViewAnim();
    }

    private void startViewAnim() {
        if (animRunnable == null) {
            animRunnable = new Runnable() {
                @Override
                public void run() {
                    if (animRunnable == null || animRunnable != this) return;
                    final int firstPosition = layoutManager.findFirstVisibleItemPosition();
                    final int lastPosition = layoutManager.findLastVisibleItemPosition();
                    List<View> viewList = new ArrayList<>();
                    for (int i = firstPosition; i <= lastPosition; i++) {
                        View view = layoutManager.findViewByPosition(i);
                        if (view == null) continue;
                        viewList.add(view);
                    }
                    boolean next = false;
                    ViewHolderAnim holderAnimTmp = animList.get(0);
                    for (int i = 0; i < viewList.size(); i++) {
                        View view = viewList.get(i);

                        ViewHolderAnim holderAnim;
                        if (i < animList.size()) {
                            holderAnim = animList.get(i);
                            if (holderAnim.canMove()) {
                                holderAnim.move();
                                next = true;
                            }
                        } else {
                            holderAnim = holderAnimTmp.cloneAnim();
                            animList.add(holderAnim);
                        }
                        int top = holderAnim.animCurrY - holderAnim.animEndY;
                        setViewTop(view, top);
                    }
                    if (next) {
                        drawerLayout.postDelayed(animRunnable, 20);
                    } else {//结束
                        while (animList.size() > 2) {//保留两个
                            animList.remove(0);
                        }
                    }
                }
            };
        }
        drawerLayout.postDelayed(animRunnable, 20);
    }

    private void setViewTop(View view, int top) {
        if (view == null) return;
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) layoutParams;
            params.topMargin = top;
            view.setLayoutParams(params);
        }
    }

    public LayoutDrawerViewHolder setOnLayoutDrawerListener(OnLayoutDrawerListener onLayoutDrawerListener) {
        this.onLayoutDrawerListener = onLayoutDrawerListener;
        return this;
    }

    public void notifyDataSetChanged() {
        adapter.notifyDataSetChanged();
    }

    public void onPageSelected(int position) {
        final int oldPos = this.selectPosition;
        this.selectPosition = position;
        if (position == 0 || position + 1 == modeList.size()) {
            layoutManager.scrollToPosition(position);
        } else {
            layoutManager.smoothScrollToPosition(recyclerView, new RecyclerView.State(), position);
        }
        setViewBg(oldPos);
        setViewBg(position);
    }

    private void setViewBg(int position) {
        View view = layoutManager.findViewByPosition(position);
        if (view == null) return;
        RecyclerView.ViewHolder childViewHolder = recyclerView.getChildViewHolder(view);
        if (childViewHolder instanceof SuperRecyclerAdapter.ViewHolder) {
            SuperRecyclerAdapter.ViewHolder holder = (SuperRecyclerAdapter.ViewHolder) childViewHolder;
            //int pos = holder.position;
            holder.setPosition(position);
        }
    }

    @Override
    public void onChangeOpen(boolean open) {
        if (open) {
            ViewGroup.LayoutParams layoutParams = layout2.getLayoutParams();
            if (layoutParams instanceof FrameLayout.LayoutParams) {
                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) layoutParams;
                params.gravity = Gravity.BOTTOM;
                layout2.setLayoutParams(params);
            }
            ViewParent parent = imgArr.getParent();
            if (parent instanceof ViewGroup) {
                ViewGroup viewGroup = (ViewGroup) parent;
                viewGroup.removeView(imgArr);
                //旋转180
                ViewHelper.setRotation(imgArr, 180);
                //更换位置
                viewGroup.addView(imgArr, 0);
            }
            parent = layout1.getParent();//layout1 换位置
            if (parent instanceof ViewGroup) {
                ViewGroup viewGroup = (ViewGroup) parent;
                viewGroup.removeView(layout1);
                ViewHelper.setRotation(layout1Bg, 180);
                viewGroup.addView(layout1, 0);
            }
        } else {
            ViewGroup.LayoutParams layoutParams = layout2.getLayoutParams();
            if (layoutParams instanceof FrameLayout.LayoutParams) {
                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) layoutParams;
                params.gravity = Gravity.TOP;
                layout2.setLayoutParams(params);
            }
            ViewParent parent = imgArr.getParent();
            if (parent instanceof ViewGroup) {
                ViewGroup viewGroup = (ViewGroup) parent;
                viewGroup.removeView(imgArr);
                ViewHelper.setRotation(imgArr, 0);
                viewGroup.addView(imgArr);
            }
            parent = layout1.getParent();//layout1 换位置
            if (parent instanceof ViewGroup) {
                ViewGroup viewGroup = (ViewGroup) parent;
                viewGroup.removeView(layout1);
                ViewHelper.setRotation(layout1Bg, 0);
                viewGroup.addView(layout1);
            }
        }
        if (onLayoutDrawerListener == null) return;
        onLayoutDrawerListener.onChangeOpen(open);
    }

    @Override
    public void onContentOffset(int paddingTop) {
        startChaseAnim(paddingTop);
        //重新计算相对位置，提供给MainLiveFragment
        if (onLayoutDrawerListener == null) return;
        final int height = drawerLayout.getHeight();
        final int contentHeight = drawerLayout.getContentHeight();
        final int buttonViewHeight = drawerLayout.getButtonViewHeight();
        final int paddMax = height - buttonViewHeight;
        float offset = (paddingTop + contentHeight) * 1.0f / paddMax * (contentHeight + buttonViewHeight);
        //(a+b)/c*(b+d)
        onLayoutDrawerListener.onContentOffset(offset);
    }

    /*@Override
    public void getRoomDetailsRet(final NewMainVideoMode videoMode, Object data) {
        addDetailsMode(videoMode, data);
        if (onLayoutDrawerListener != null)
            onLayoutDrawerListener.onDrawerRoomDetailsRet(videoMode, data);
        int position = modeList.indexOf(videoMode);
        if (position < 0) return;
        View view = layoutManager.findViewByPosition(position);
        RecyclerView.ViewHolder childViewHolder = view == null ? null : recyclerView.getChildViewHolder(view);
        if (childViewHolder instanceof SuperRecyclerAdapter.ViewHolder) {
            SuperRecyclerAdapter.ViewHolder holder = (SuperRecyclerAdapter.ViewHolder) childViewHolder;
            holder.setData(videoMode);
            //int pos = holder.position;
            holder.setPosition(position);
        } else adapter.notifyItemChanged(position);
    }

    public void addDetailsMode(String contentId, Object object) {
        if (TextUtils.isEmpty(contentId)) return;
        NewMainVideoMode videoMode = null;
        int position = 0;
        for (int i = 0; i < modeList.size(); i++) {
            NewMainVideoMode mainVideoMode = modeList.get(i);
            if (contentId.equals(mainVideoMode.contentId)) {
                videoMode = mainVideoMode;
                position = i;
                break;
            }
        }
        if (videoMode == null) return;
        addDetailsMode(videoMode, object);
        View view = layoutManager.findViewByPosition(position);
        RecyclerView.ViewHolder childViewHolder = view == null ? null : recyclerView.getChildViewHolder(view);
        if (childViewHolder instanceof SuperRecyclerAdapter.ViewHolder) {
            SuperRecyclerAdapter.ViewHolder holder = (SuperRecyclerAdapter.ViewHolder) childViewHolder;
            holder.setData(videoMode);
            holder.setPosition(position);
        } else adapter.notifyItemChanged(position);
    }

    private Object getDetailsMode(NewMainVideoMode videoMode) {
        return detailsModeMap.get(videoMode);
    }

    private void addDetailsMode(NewMainVideoMode videoMode, Object object) {
        detailsModeMap.put(videoMode, object);
        clearOtherMap();
    }

    private void clearOtherMap() {
        if (detailsModeMap.size() < 15) return;
        List<NewMainVideoMode> list = new ArrayList<>(20);
        Set<NewMainVideoMode> keySet = detailsModeMap.keySet();
        for (NewMainVideoMode videoMode : keySet) {
            if (modeList.contains(videoMode)) continue;
            list.add(videoMode);
        }
        for (int i = 0; i < list.size(); i++) {
            NewMainVideoMode videoMode = list.get(i);
            detailsModeMap.remove(videoMode);
        }
        list.clear();
    }*/

    public void onDestroy() {
        /*if (presenter != null) presenter.onDestroy();
        presenter = null;*/
    }

    public class LayoutDrawerAdapter extends SuperRecyclerAdapter<NewMainVideoMode> {
        public LayoutDrawerAdapter(Context context, List<NewMainVideoMode> modeList) {
            super(context, modeList);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_main_live_toplist;
        }

        @Override
        public ViewHolder<NewMainVideoMode> getViewHolder(View view) {
            return new LayoutDrawerItemViewHolder(view);
        }

        @Override
        public void onViewDetachedFromWindow(@NonNull ViewHolder holder) {
            if (holder instanceof LayoutDrawerItemViewHolder) {
                LayoutDrawerItemViewHolder viewHolder = (LayoutDrawerItemViewHolder) holder;
                viewHolder.position = -1;
            }
        }
    }

    private static final int colorRounded = 0xffFC5B3F;
    private int selectPosition;
    //private String _小时前, _1小时, _1天, _天前, _小时内, _天内;

    public class LayoutDrawerItemViewHolder extends SuperRecyclerAdapter.ViewHolder<NewMainVideoMode> {
        @BindView(R.id.icon)
        ImageView icon;
        @BindView(R.id.layoutBg)
        RoundedImageView layoutBg;

        LayoutDrawerItemViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            layoutBg.setOnClickListener(v -> {
                if (mode == null || onLayoutDrawerListener == null) return;
                onLayoutDrawerListener.onLayoutDrawerClick(mode);
            });
        }

        @Override
        public void setPosition(int position) {
            super.setPosition(position);
            if (position == selectPosition) {
                layoutBg.setBorderColor(-1);
            } else {
                layoutBg.setBorderColor(colorRounded);
            }
            /*if (selectPosition != position) return;
            String s = textTime.getText().toString();
            if (TextUtils.isEmpty(s)) return;
            textMakeAnLive.setText(s);
            imgLive.setVisibility(isBanner ? View.GONE : imgGif.getVisibility());*/
        }

        @Override
        public void setData(NewMainVideoMode mode) {
            super.setData(mode);
            if (mode.contentType == -3) {
                BannerMode bannerMode = mode.bannerMode;
                if (bannerMode == null) return;
                GlideUtils.displayOfUrl(activity, icon, bannerMode.getImageUrl());
            } /*else {
                Object object = getDetailsMode(mode);
                if (mode.contentType == 1) {
                    imgGif.setVisibility(View.VISIBLE);
                    if (object instanceof LiveRoomDetailsMode) {
                        LiveRoomDetailsMode detailsMode = (LiveRoomDetailsMode) object;

                        AnchorMode anchorMode = detailsMode.liveHostInfo;
                        GlideUtils.displayOfUrl(activity, imgUserIcon, anchorMode.getImg());
                        textName.setText(anchorMode.userName);
                        String noticeImg = detailsMode.getImg();
                        GlideUtils.displayOfUrl(activity, icon, noticeImg);

                        //时间
                        long bookStartTime = detailsMode.bookStartTime;
                        SimpleDateFormat dateFormat = new SimpleDateFormat(AppConstant.isZh() ? AppConstant.TimeFrom4 : AppConstant.TimeFrom4En);
                        String format = dateFormat.format(bookStartTime);
                        textTitle.setText(format + '\n' + detailsMode.liveName);
                        textTime.setText(R.string.live);
                    } else {
                        setViewNullData();
                        presenter.getRoomDetails(mode);
                    }
                } else if (mode.contentType == 4 || mode.contentType == -1) {//回放
                    imgGif.setVisibility(View.GONE);
                    if (object instanceof LiveBackDetailsMode) {
                        LiveBackDetailsMode detailsMode = (LiveBackDetailsMode) object;

                        AnchorMode anchorMode = detailsMode.liveHostInfo;
                        GlideUtils.displayOfUrl(activity, imgUserIcon, anchorMode.getImg());
                        textName.setText(anchorMode.userName);
                        String noticeImg = detailsMode.getImg();
                        GlideUtils.displayOfUrl(activity, icon, noticeImg);

                        //时间
                        long bookStartTime = detailsMode.startTime;
                        SimpleDateFormat dateFormat = new SimpleDateFormat(AppConstant.isZh() ? AppConstant.TimeFrom4 : AppConstant.TimeFrom4En);
                        String format = dateFormat.format(bookStartTime);
                        textTitle.setText(format + '\n' + detailsMode.liveName);

                        long timeMillis = System.currentTimeMillis();
                        long timeLen = timeMillis - bookStartTime;//时长
                        if (timeLen > TimeConstant._24H) {//_天前
                            long hour = timeLen / 1000 / 60 / 60;//多少小时
                            if (hour == 24) {
                                textTime.setText(_1天);
                            } else {
                                float v = hour * 1.0f / 24;
                                DecimalFormat df = new DecimalFormat("######0");
                                textTime.setText(String.format(_天前, df.format(v)));
                            }
                        } else {//_小时前
                            long m = timeLen / 1000 / 60;//多少分钟
                            if (m < 60) {
                                String timeMsg = AppConstant.getTimeMsg(timeLen);
                                textTime.setText(timeMsg);
                            } else if (m == 60) {
                                textTime.setText(_1小时);
                            } else {
                                float v = m * 1.0f / 60;
                                DecimalFormat df = new DecimalFormat("######0");
                                textTime.setText(String.format(_小时前, df.format(v)));
                            }
                        }
                    } else {
                        setViewNullData();
                        presenter.getBackPlayDetails(mode);
                    }
                } else if (mode.contentType == 5 || mode.contentType == -2) {
                    imgGif.setVisibility(View.GONE);
                    if (object instanceof LiveNoticeDetailsMode) {
                        LiveNoticeDetailsMode detailsMode = (LiveNoticeDetailsMode) object;

                        AnchorMode anchorMode = detailsMode.liveHostInfo;
                        GlideUtils.displayOfUrl(activity, imgUserIcon, anchorMode.getImg());
                        textName.setText(anchorMode.userName);
                        String noticeImg = detailsMode.getImg();
                        GlideUtils.displayOfUrl(activity, icon, noticeImg);

                        //时间
                        long bookStartTime = detailsMode.bookStartTime;
                        SimpleDateFormat dateFormat = new SimpleDateFormat(AppConstant.isZh() ? AppConstant.TimeFrom4 : AppConstant.TimeFrom4En);
                        String format = dateFormat.format(bookStartTime);
                        textTitle.setText(format + '\n' + detailsMode.liveName);
                        //textTime.setText(R.string.live);

                        long timeMillis = System.currentTimeMillis();
                        long timeLen = bookStartTime - timeMillis;//时长
                        if (timeLen > TimeConstant._24H) {//_天内
                            long hour = timeLen / 1000 / 60 / 60;//多少小时
                            if (hour == 24) {
                                textTime.setText(_1天);
                            } else {
                                float v = hour * 1.0f / 24;
                                DecimalFormat df = new DecimalFormat("######0");
                                textTime.setText(String.format(_天内, df.format(v)));
                            }
                        } else {//_小时内
                            long m = timeLen / 1000 / 60;//多少分钟
                            if (m < 60) {
                                textTime.setText(String.format(_小时内, String.valueOf(1)));
                            } else if (m == 60) {
                                textTime.setText(_1小时);
                            } else {
                                float v = m * 1.0f / 60;
                                DecimalFormat df = new DecimalFormat("######0");
                                textTime.setText(String.format(_小时内, df.format(v)));
                            }
                        }
                    } else {
                        setViewNullData();
                        presenter.getNoticeDetails(mode);
                    }
                }
            }*/
        }

        /*private void setViewNullData() {
            Glide.with(activity)
                    .load(R.mipmap.img_load_err)
                    .apply(new RequestOptions())
                    .into(icon);
            Glide.with(activity)
                    .load(R.mipmap.img_load_err)
                    .apply(new RequestOptions())
                    .into(imgUserIcon);
            textTitle.setText(null);
            textTime.setText(null);
            textName.setText(null);
        }*/
    }

    public interface OnLayoutDrawerListener {
        void onChangeOpen(boolean open);

        void onLayoutDrawerClick(NewMainVideoMode mode);

        void onContentOffset(float offset);

        //void onDrawerRoomDetailsRet(NewMainVideoMode videoMode, Object data);
    }

    public class ViewHolderAnim {
        private static final float Rub = 0.45f;//摩擦
        public int animCurrY;//动画当前位置或开始位置 -ContentHeight
        public int animEndY;//动画要追逐的位置 当前的paddingTop
        public float animV;//速度
        public float animG;//动态加速度
        public float animGB;//这个决定最大的加速度
        private float maxG;

        public ViewHolderAnim(int animCurrY, int animEndY) {
            this.animCurrY = animCurrY;
            this.animEndY = animEndY;
            animGB = 600 + random.nextInt(300);
            maxG = (10 + random.nextInt(10)) / 10.0f;
        }

        public ViewHolderAnim(int animCurrY, int animEndY, float animV) {
            this.animCurrY = animCurrY;
            this.animEndY = animEndY;
            this.animV = animV;
            animGB = 600 + random.nextInt(300);
            maxG = (10 + random.nextInt(10)) / 10.0f;
        }

        public ViewHolderAnim setAnimEndY(int animEndY) {
            this.animEndY = animEndY;
            return this;
        }

        /**
         * @return 是否有必要执行move
         */
        public boolean canMove() {
            //float g = animG * 2;
            int len = animEndY - animCurrY;//距离
            //return Math.abs(animV) > animG || Math.abs(len) > animV;
            //if (Math.abs(animV) <= animG && Math.abs(len) <= 2) return false;else return true;
            return !(Math.abs(animV) <= 1) || Math.abs(len) > 2;
        }


        public void move() {
            int len = animCurrY - animEndY;//距离
            animG = -len / animGB;
            if (animG > maxG) animG = maxG;
            else if (animG < -2.0f) animG = -2.0f;
            animV += animG;
            animCurrY = (int) (animCurrY + animV);
            if (len > 0) {
                if (animCurrY - animEndY < 0) animV = Rub * animV;//减速
            } else if (animCurrY - animEndY > 0) animV = Rub * animV;//减速
            /*if (animV > 0) {
                if (animCurrY >= animEndY) {//碰撞
                    animCurrY = animEndY - len;
                    animV = -(Rub * animV);
                }
            }*/
        }

        public ViewHolderAnim cloneAnim() {
            return new ViewHolderAnim(animCurrY, animEndY, animV);
        }
    }
}
